package com.one.common.location_service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.content.Intent;
import android.os.Build;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.one.common.common.LocationModel;
import com.one.common.common.system.SystemModel;
import com.one.common.common.system.model.param.UploadGpsParam;
import com.one.common.common.system.model.response.DefaultResponse;
import com.one.common.common.system.model.response.TrackResponse;
import com.one.common.config.CMemoryData;
import com.one.common.config.CPersisData;
import com.one.common.location_service.track.TrackHandle;
import com.one.common.model.http.callback.ObserverOnNextListener;
import com.one.common.receiver.NotificationHandle;
import com.one.common.utils.DelayUtils;
import com.one.common.utils.Logger;
import com.one.common.utils.NetStatusUtil;
import com.one.common.utils.StringUtils;
import com.one.common.utils.map.LocationUtils;
import com.tencent.bugly.crashreport.CrashReport;


/**
 * Author: zhulunjun
 * Email: zhulunjun@qq.com
 * CreateDate: 2019/5/24 16:41
 * Description：
 **/
public class LocationService extends NotificationService {
    private AMapLocationClient mLocationClient;
    //    private AMapLocationClientOption mLocationOption;
    private static final String TAG = "LocationService";
    /**
     * 处理息屏关掉wifi的delegate类
     */
    private IWifiAutoCloseDelegate mWifiAutoCloseDelegate = new WifiAutoCloseDelegate();

    /**
     * 记录是否需要对息屏关掉wifi的情况进行处理
     */
    private boolean mIsWifiCloseable = false;
    private Notification notification;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        notification = applyNotiKeepMech(); //开启利用notification提高进程优先级的机制
        if (mWifiAutoCloseDelegate.isUseful(getApplicationContext())) {
            mIsWifiCloseable = true;
            mWifiAutoCloseDelegate.initOnServiceStarted(getApplicationContext());
        }

        startLocation();

        starTrackService();

        if (CPersisData.getIsLogin()) {
            return START_NOT_STICKY;
        } else {
            return START_STICKY;
        }
    }

    /**
     * 3次重试
     */
    private int reRequestNum =0;
    private void starTrackService(){
        new LocationModel().getTrackInfo(new ObserverOnNextListener<TrackResponse>() {
            @Override
            public void onNext(TrackResponse trackResonse) {
                if(trackResonse!=null) {
                    if (StringUtils.isNotBlank(trackResonse.getErrcode()) && trackResonse.getErrcode().equals("10000")) {
                        CMemoryData.setTrackBean(trackResonse.getTerminal());
                        // 开启猎鹰轨迹采集
                        TrackHandle.getInstance().startTrack(notification);
                    } else {
                        CrashReport.postCatchedException(new Throwable("轨迹接口错误 " + trackResonse.getErrcode() + " " + trackResonse.getErrmsg()));
                    }
                }
            }

            @Override
            public void onError(String errorCode, String msg) {
                Logger.d("轨迹接口错误 onError" + errorCode + " " + msg);
                DelayUtils.delay(2000, () -> {
                    if(reRequestNum > 3){
                        reRequestNum = 0;
                        CrashReport.postCatchedException(new Throwable("轨迹接口错误 onError" + errorCode + " " + msg));
                    }else {
                        reRequestNum++;
                        // 暂停采集
                        starTrackService();
                    }
                });
            }
        });
    }


    @Override
    public void onDestroy() {
        // 关闭猎鹰轨迹采集
        TrackHandle.getInstance().stopTrack();

        unApplyNotiKeepMech();
        stopLocation();
        closeNotify();

        super.onDestroy();
    }

    /**
     * 启动定位
     */
    void startLocation() {
        stopLocation();

        if (null == mLocationClient) {
            mLocationClient = new AMapLocationClient(this.getApplicationContext());
        }

//        mLocationOption = new AMapLocationClientOption();
//        // 使用连续
//        mLocationOption.setOnceLocation(true);
//        mLocationOption.setLocationCacheEnable(false);
//        // 每5秒定位一次
//        mLocationOption.setInterval(30*1000L);
//        // 地址信息
//        mLocationOption.setNeedAddress(true);
        mLocationClient.setLocationOption(LocationUtils.getDefaultOption());
        mLocationClient.setLocationListener(locationListener);
        mLocationClient.startLocation();
    }

    /**
     * 停止定位
     */
    void stopLocation() {
        if (null != mLocationClient) {
            mLocationClient.stopLocation();
        }
    }

    AMapLocationListener locationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            //发送结果的通知
            sendLocationBroadcast(aMapLocation);

            if (!mIsWifiCloseable) {
                return;
            }

            if (aMapLocation.getErrorCode() == AMapLocation.LOCATION_SUCCESS) {
                mWifiAutoCloseDelegate.onLocateSuccess(getApplicationContext(),
                        PowerManagerUtil.getInstance().isScreenOn(getApplicationContext()),
                        NetStatusUtil.isNetworkAvailable(getApplicationContext()));
            } else {
                mWifiAutoCloseDelegate.onLocateFail(getApplicationContext(),
                        aMapLocation.getErrorCode(), PowerManagerUtil.getInstance().isScreenOn(getApplicationContext()),
                        NetStatusUtil.isNetworkAvailable(getApplicationContext()));
            }

        }

        private void sendLocationBroadcast(AMapLocation aMapLocation) {
            if (null != aMapLocation) {

                Logger.d(TAG, "定位回调  FixedCycleLocationService  " + (aMapLocation != null));
                if (aMapLocation != null && aMapLocation.getLongitude() > 0 && aMapLocation.getLatitude() > 0) {
                    Logger.d(TAG, "定位成功  FixedCycleLocationService");
                    UploadGpsParam locationInfo = new UploadGpsParam(aMapLocation);
                    // 在内存中存储定位信息
                    CMemoryData.setLocationInfo(locationInfo);
                    if (StringUtils.isNotBlank(CMemoryData.getUserMobile()) && CPersisData.getIsLogin()) {
                        requestServer(locationInfo);
                    } else {
                        Logger.e(TAG, "用户未登录缺少请求头字段mobile");
                    }
                }
            }
        }
    };


    /**
     * 车主上传定位信息
     */
    private void requestServer(final UploadGpsParam params) {
        Logger.d(TAG, params.toString());
        new SystemModel().uploadGps(params, new ObserverOnNextListener<DefaultResponse>() {
            @Override
            public void onNext(DefaultResponse object) {
                Logger.d(TAG, "上传定位信息至服务器成功  FixedCycleLocationService");
            }

            @Override
            public void onError(String errorCode, String msg) {
                Logger.e(TAG, "上传定位信息至服务器失败  FixedCycleLocationService");
            }
        });

//        new SystemModel().getOrderState(new ObserverOnNextListener<OrderStateResponse>() {
//
//            @Override
//            public void onNext(OrderStateResponse orderStateResponse) {
//                if (!orderStateResponse.getIs_transiting()) {
//                    closeNotify();
//                } else {
////                    setNotification();
//                }
//            }
//
//            @Override
//            public void onError(String errorCode, String msg) {
////                setNotification();
//            }
//        });

    }

    @SuppressLint("WrongConstant")
    public void closeNotify() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(NOTI_ID);
            stopForeground(true);
        } else {
            new NotificationHandle(LocationService.this)
                    .getManager().cancel(NOTI_ID);
        }
    }
}
